﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Threading;
using System.Globalization;

namespace XLDL.Admin
{
    public partial class SanPham : System.Web.UI.UserControl
    {
         string path = System.Configuration.ConfigurationManager.AppSettings["Images_Path"];
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["gt"].ToString() != "")
                {
                    for (int i = 0; i < Drop_timgt.Items.Count; i++)
                    {
                        if (Session["gt"].ToString() == Drop_timgt.Items[i].ToString())
                        {
                            Drop_timgt.SelectedIndex = i;
                            break;
                        }
                    }
                }
                this.Button_tim.Focus();
                Nhom_sp();
                Xuat_luoi(Drop_timgt);
                
            }
            
        }
        protected void Xuat_luoi(DropDownList dr)
        {
            this.Button_tim.Focus();
            DataTable tb = new DataTable();
            string lenh = "";
           // string tk = "";
          //  lbl_tk.Text = Drop_timgt.SelectedItem.ToString();
            if (dr.Enabled == true)
            {
                // tim bang gioi tinh

                if (dr.SelectedValue.ToString() != "all")
                {
                    //int i=Drop_timgt.SelectedIndex;
                    if (Drop_timgt.SelectedItem.ToString().ToLower() == "nam" || Drop_timgt.SelectedItem.ToString().ToLower() == "nữ" || Drop_timgt.SelectedItem.ToString().ToLower() == "đôi")
                    {
                        lenh = "select * from V_sanpham_admin where gioi_tinh_sp=N'" + Drop_timgt.SelectedItem.ToString() + "' order by ngay_dang_sp DESC";
                    }
                    else if (Drop_timgt.SelectedItem.ToString().ToLower() == "còn hàng" || Drop_timgt.SelectedItem.ToString().ToLower() == "hết hàng" || Drop_timgt.SelectedItem.ToString().ToLower() == "sắp về")
                 
                    {

                        lenh = "select * from V_sanpham_admin where tinh_trang=" + int.Parse(Drop_timgt.SelectedValue.ToString()) + " order by ngay_dang_sp DESC";
                    }
                    else if (Drop_timgt.SelectedItem.ToString().ToLower() == "ẩn" || Drop_timgt.SelectedItem.ToString().ToLower() == "hiện")
                 
                    {
                        lenh = "select * from V_sanpham_admin where hien_thi='" + Drop_timgt.SelectedValue.ToString() + "' order by ngay_dang_sp DESC";
                    }
                    else if (Drop_timgt.SelectedItem.ToString().ToLower() == "mới")
                    {
                        lenh = "select * from V_sanpham_admin where moi_cu='True' order by ngay_dang_sp DESC";
                    }
                    else if (Drop_timgt.SelectedItem.ToString().ToLower() == "cũ")
                    {
                        lenh = "select * from V_sanpham_admin where moi_cu='False' order by ngay_dang_sp DESC";
                    }
                    else if (Drop_timgt.SelectedItem.ToString().ToLower() == "hot")
                    {
                        lenh = "select * from V_sanpham_admin where hot='True' order by ngay_dang_sp DESC";
                    }
                   
                }
                else
                {
                    lenh = "select * from V_sanpham_admin order by ngay_dang_sp DESC";
                }
            }
            else
            {
                // tim bang id
                lenh = "select * from V_sanpham_admin where id_sp=" + int.Parse(txt_tim.Text) + " order by ngay_dang_sp DESC";

            }
            
            tb = XLDL.XLDaTa(lenh);
            CollectionPager1.PageSize = 10;
            CollectionPager1.DataSource = tb.DefaultView;
            CollectionPager1.BindToControl =Luoi;
            Luoi.DataSource = CollectionPager1.DataSourcePaged;
            Luoi.DataBind();
            Luoi.Columns[9].Visible = true;
            lbl_tongcong.Text ="Tổng số sản phẩm "+Drop_timgt.SelectedItem.ToString()+" : " +tb.Rows.Count.ToString();
            Session["gt"] = Drop_timgt.SelectedItem.ToString();
            CollectionPager1.Visible = true;
            Button_more.Visible = true;
            if (lbl_id.Text == "")
            {
                Button_more.Visible = false;
            }
            if (tb.Rows.Count == 0)
            {
                CollectionPager1.Visible = false;
                lbl_tongcong.Text = "Không tìm thấy sản phẩm nào !";
            }
            if (tb.Rows.Count == 1)
            {
                CollectionPager1.Visible = false;
            }
        }
        protected void Nhom_sp()
        {
            DataTable tb = new DataTable();
            string lenh = "select * from nhom_sanpham order by ten_nhom_sp ASC";
            tb = XLDL.XLDaTa(lenh);
            Drop_nhomsp.DataSource = tb;
            Drop_nhomsp.DataTextField = "ten_nhom_sp";
            Drop_nhomsp.DataValueField = "id_nhom_sp";
            Drop_nhomsp.DataBind();
            
        }

        protected void Luoi_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            
                Label id = (Label)Luoi.Rows[e.NewSelectedIndex].Cells[0].FindControl("lbl_id");
                lbl_id.Text = id.Text;
                Nhom_sp();

                tim_sp(int.Parse(id.Text));
                Xuat_luoi(Drop_timgt);
           
            
        }
        protected void tim_sp(int id)
        {
            DataTable tb = new DataTable();
            string lenh = "select * from V_sanpham_admin where id_sp=" + id + "";
            tb = XLDL.XLDaTa(lenh);
            //ngay dang
            DateTime dt = Convert.ToDateTime(tb.Rows[0]["ngay_dang_sp"].ToString());
            txt_ngaydang.Text = dt.ToString("dd/MM/yyyy");
            //ten sp
            this.txt_tensp.Text = tb.Rows[0]["ten_sp"].ToString();
            //nhom sp
          //  string id_nhom = tb.Rows[0]["id_nhom_sp"].ToString();
            for (int i = 0; i < Drop_nhomsp.Items.Count; i++)
            {
                if (Drop_nhomsp.Items[i].Value.ToString() == tb.Rows[0]["id_nhom_sp"].ToString())
                {
                    Drop_nhomsp.SelectedIndex = i;
                    break;
                }
            }
            //gioi tinh
          //  string gt = tb.Rows[0]["gioi_tinh_sp"].ToString();
            for (int i = 0; i < Drop_gioitinh.Items.Count; i++)
            {
                if (Drop_gioitinh.Items[i].Value.ToString().ToLower() == tb.Rows[0]["id_gt"].ToString().ToLower())
                {
                    Drop_gioitinh.SelectedIndex = i;
                    break;
                }
            }
            //Gia
            string gia=tb.Rows[0]["gia_sp"].ToString();
            this.txt_gia.Text =gia.Remove(gia.LastIndexOf(".")) ;
            //tinh trang
        //    string tt = tb.Rows[0]["tinh_trang"].ToString();
            for (int i = 0; i < Drop_tinhtrang.Items.Count; i++)
            {
                if (Drop_tinhtrang.Items[i].Value.ToString().ToLower() == tb.Rows[0]["tinh_trang"].ToString().ToLower())
                {
                    Drop_tinhtrang.SelectedIndex = i;
                    break;
                }
            }
            //moi cu
           // string moicu = tb.Rows[0]["tinh_trang"].ToString();
            for (int i = 0; i < Drop_moicu.Items.Count; i++)
            {
                if (Drop_moicu.Items[i].Value.ToString().ToLower() == tb.Rows[0]["moi_cu"].ToString().ToLower())
                {
                    Drop_moicu.SelectedIndex = i;
                    break;
                }
            }
            //hot
            for (int i = 0; i < Drop_hot.Items.Count; i++)
            {
                if (Drop_hot.Items[i].Value.ToString().ToLower() == tb.Rows[0]["hot"].ToString().ToLower())
                {
                    Drop_hot.SelectedIndex = i;
                    break;
                }
            }
            // hien thi
            for (int i = 0; i < Drop_hienthi.Items.Count; i++)
            {
                if (Drop_hienthi.Items[i].Value.ToString().ToLower() == tb.Rows[0]["hien_thi"].ToString().ToLower())
                {
                    Drop_hienthi.SelectedIndex = i;
                    break;
                }
            }
            //mot ta
           
            this.mo_ta.Content = tb.Rows[0]["mo_ta"].ToString();
            // ID
           
            //hinh anh
            lbl_hinhanh.Text = tb.Rows[0]["hinh_anh"].ToString();
            string path = System.Configuration.ConfigurationManager.AppSettings["Images_Path"];
            Image_hinh_anh.ImageUrl = "~/"+path + lbl_hinhanh.Text;
            Luoi.DataSource = tb;
            Luoi.DataBind();
            if (tb.Rows.Count < 2)
            {
                CollectionPager1.Visible = false;
            }
            else
            {
                CollectionPager1.Visible = true;
            }
          
        }
        protected void Button_open_Click(object sender, EventArgs e)
        {
           
        }

        protected void Button_tim_Click(object sender, EventArgs e)
        {
            Xuat_luoi(Drop_timgt);
        }

        protected void txt_tim_TextChanged(object sender, EventArgs e)
        {
            if (txt_tim.Text != "")
            {
               // Drop_timgt.Items.Clear();
                Drop_timgt.Items.Add("ID");
                Drop_timgt.SelectedIndex =Drop_timgt.Items.Count-1;
                Drop_timgt.Enabled = false;
              
            }
            else
            {
                Drop_timgt.Items.RemoveAt(Drop_timgt.Items.Count-1);
                Drop_timgt.Enabled = true;
            }
        }

        protected void Button_sua_Click(object sender, EventArgs e)
        {
            DataTable tb = new DataTable();
            string hinh = "";
            if (fu_hinhanh.HasFile == true)
            {
                if (lbl_hinhanh.Text != fu_hinhanh.FileName)
                {
                    System.IO.File.Delete(Server.MapPath(path + lbl_hinhanh.Text));
                    hinh = fu_hinhanh.FileName;
                    fu_hinhanh.SaveAs(Server.MapPath(path + fu_hinhanh.FileName));
                }
                else
                {
                    hinh = lbl_hinhanh.Text;
                }
            }
            else
            {
                hinh = lbl_hinhanh.Text;
            }

            string ngay = "";
            if (txt_ngaydang.Text != "" && lbl_id.Text != "")
            {
                // Sys re = new System.Globalization.CultureInfo("en-US", false);
                //     System.DateTime str_date = DateTime.Parse(txt_ngaydang.Text, System.Globalization.CultureInfo.CreateSpecificCulture("en-US").DateTimeFormat);
               
                    DateTime dt = DateTime.Parse(txt_ngaydang.Text.Trim(), new CultureInfo("en-GB"));// Convert.ToDateTime(txt_ngaydang.Text.ToString().Trim()).ToString("M-d-yyyy ") + DateTime.Now.ToShortTimeString();
                    ngay = dt.ToString("M/d/yyyy ") + DateTime.Now.ToShortTimeString();
                    string lenh = "update san_pham set ngay_dang_sp='" + ngay + "', ten_sp=N'" + txt_tensp.Text + "', id_nhom_sp=" + int.Parse(Drop_nhomsp.SelectedValue.ToString()) + ", id_gt=" + int.Parse(Drop_gioitinh.SelectedValue.ToString()) + ", gia_sp=" + int.Parse(txt_gia.Text.Trim()) + ", tinh_trang='" + Drop_tinhtrang.SelectedValue.ToString() + "', moi_cu='" + Drop_moicu.SelectedValue.ToString() + "', hot='" + Drop_hot.SelectedValue.ToString() + "', hien_thi='" + Drop_hienthi.SelectedValue.ToString() + "', mo_ta=N'" + mo_ta.Content + "', hinh_anh='" + hinh + "' where id_sp=" + int.Parse(lbl_id.Text) + "";
                    tb = XLDL.XLDaTa(lenh);
                    // Xuat_sua(lbl_id.Text);
                    tim_sp(int.Parse(lbl_id.Text));
                    Luoi.Columns[9].Visible = false;
               
            }
            else
            {
                reset();
                lbl_tongcong.Text = "Vui lòng chọn sản phẩm để Sửa !";
            }
            
        }

        //protected void Xuat_sua(string id)
        //{
        //    DataTable tb = new DataTable();
        //    string lenh = "select * from san_pham where id_sp=" + int.Parse(id) + "";
        //    tb = XLDL.XLDaTa(lenh);
        //    CollectionPager1.PageSize = 8;
        //    CollectionPager1.DataSource = tb.DefaultView;
        //    CollectionPager1.BindToControl = Luoi;
        //    Luoi.DataSource = CollectionPager1.DataSourcePaged;
        //    Luoi.DataBind();
        //    Luoi.Columns[9].Visible = false;
        //    Image_hinh_anh.ImageUrl = "~/"+path + tb.Rows[0]["hinh_anh"].ToString();
        //    lbl_hinhanh.Text = tb.Rows[0]["hinh_anh"].ToString();
        //    CollectionPager1.Visible = false;
        //}

        protected void lich_SelectionChanged(object sender, EventArgs e)
        {
            txt_ngaydang.Text = "";
            txt_ngaydang.Text = lich.SelectedDate.ToString("dd/MM/yyyy");
             Xuat_luoi(Drop_timgt);
        }

        protected void open_Click(object sender, EventArgs e)
        {
            if (this.up_editor.Visible == false)
            {
                this.up_editor.Visible = true;
            }
            else
            {
                this.up_editor.Visible = false;
            }
            Xuat_luoi(Drop_timgt);
        }

        protected void Button_them_Click(object sender, EventArgs e)
        {
            DataTable tb = new DataTable();           
            //try
            //{
           
            if (fu_hinhanh.HasFile == true)
            {
                string hinh = "";
                string ngay = "";
                if (txt_ngaydang.Text != "")
                {
                   // ngay = Convert.ToDateTime(txt_ngaydang.Text.ToString()).ToString("M-d-yyyy ") + DateTime.Now.ToShortTimeString();
                    DateTime dt = DateTime.Parse(txt_ngaydang.Text.Trim(), new CultureInfo("en-GB"));// Convert.ToDateTime(txt_ngaydang.Text.ToString().Trim()).ToString("M-d-yyyy ") + DateTime.Now.ToShortTimeString();
                    ngay = dt.ToString("M/d/yyyy ") + DateTime.Now.ToShortTimeString();
                }
                if (System.IO.File.Exists(Server.MapPath(path + fu_hinhanh.FileName)) == false)
                {
                    //    System.IO.File.Delete(Server.MapPath(path + lbl_hinhanh.Text));
                    hinh = fu_hinhanh.FileName;
                    fu_hinhanh.SaveAs(Server.MapPath(path + fu_hinhanh.FileName));

                    string lenh = "insert into san_pham (ngay_dang_sp,ten_sp,id_nhom_sp,id_gt,gia_sp,tinh_trang,moi_cu,hot,hien_thi,mo_ta,hinh_anh,newicon,id_hang) values('" + ngay + "', N'" + txt_tensp.Text + "'," + int.Parse(Drop_nhomsp.SelectedValue.ToString()) + "," + int.Parse(Drop_gioitinh.SelectedValue.ToString()) + "," + int.Parse(txt_gia.Text.Trim()) + ",'" + Drop_tinhtrang.SelectedValue.ToString() + "','" + Drop_moicu.SelectedValue.ToString() + "','" + Drop_hot.SelectedValue.ToString() + "','" + Drop_hienthi.SelectedValue.ToString() + "',N'" + mo_ta.Content + "','" + hinh + "','new_icon.gif',1)";
                    tb = XLDL.XLDaTa(lenh);
                    tb.Clear();
                    lenh = "select ident_current ('san_pham') as [id]";
                    tb = XLDL.XLDaTa(lenh);
                    //gan id query string 
                    lbl_id.Text = tb.Rows[0]["id"].ToString();
                    this.Button_more.Visible = true;

                    tim_sp(int.Parse(tb.Rows[0]["id"].ToString()));
                    CollectionPager1.Visible = true;
                    lbl_tongcong.Text = "Sản phẩm đã nhập thành công !";
                }

                else
                {
                    reset();
                    lbl_tongcong.Text = " Sản phẩm đã tồn tại hoặc chọn hình để nhập SP mới !";
                }
              
            }
            else
            {
                reset();
                lbl_tongcong.Text = " Sản phẩm đã tồn tại hoặc chọn hình để nhập SP mới !";
            }
                
          //  }
          //  catch { }
        }
        protected void reset()
        {
         CollectionPager1.Visible = false;
            Luoi.DataSource = "";
            Luoi.DataBind();
        }
        protected void Button_xoa_Click(object sender, EventArgs e)
        {
            if (lbl_id.Text != "")
            {
                DataTable tb = new DataTable();
                // xoa hinh anh theo truoc
                tb = XLDL.XLDaTa("select * from Hinh_anh where id_sp=" + int.Parse(lbl_id.Text) + "");
                if (tb.Rows.Count > 0)
                {
                    for (int i = 0; i < tb.Rows.Count; i++)
                    {
                        System.IO.File.Delete(Server.MapPath(path + tb.Rows[i]["hinh_anh_2"].ToString()));
                    }
                }
                    // xoa hinh chinh
                tb.Clear();
                tb = XLDL.XLDaTa("delete from San_pham where id_sp=" + int.Parse(lbl_id.Text) + "");
                System.IO.File.Delete(Server.MapPath(path + lbl_hinhanh.Text));
                lbl_id.Text = "";
                Image_hinh_anh.ImageUrl = "~/Images/Tao.jpg";
                lbl_hinhanh.Text = "";
                Xuat_luoi(Drop_timgt);
            }
            else
            {
                CollectionPager1.Visible = false;
                lbl_tongcong.Text = " Vui lòng chọn Sản phẩm để xoá !";
                Luoi.DataSource = "";
                Luoi.DataBind();
            }
        }

        protected void Luoi_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            foreach (GridViewRow row in Luoi.Rows)
            {
                Label tinhtrang = (Label)row.FindControl("lbl_tinhtrang");
                if (tinhtrang.Text == "0")
                {
                    tinhtrang.Text = "Hết hàng";
                }
                if (tinhtrang.Text == "1")
                    {
                        tinhtrang.Text = "Còn hàng";
                    }
                     if (tinhtrang.Text == "2")
                    {
                        tinhtrang.Text = "Sắp về";
                    }
                  Label moicu = (Label)row.FindControl("lbl_moicu");
                  if (moicu.Text == "True")
                  {
                      moicu.Text = "Mới";
                  }
                  if (moicu.Text == "False")
                  {
                      moicu.Text = "Cũ";
                  }
                  //Label ht = (Label)row.FindControl("lbl_ht");
                  //if (ht.Text == "True")
                  //{
                  //    ht.Text = "Hiện";
                  //}
                  //if (ht.Text == "False")
                  //{
                  //    ht.Text = "Ẩn";
                  //}
               
            }
           
              
            
        }

        protected void Luoi_RowCreated(object sender, GridViewRowEventArgs e)
        {
            //Label tinhtrang = ((Label)e.Row.FindControl("lbl_tinhtrang"));
        }

        protected void Luoi_DataBound(object sender, EventArgs e)
        {
            //Label tinhtrang = ((Label)Luoi.FindControl("lbl_tinhtrang"));
        }

       

        protected void Drop_timgt_SelectedIndexChanged(object sender, EventArgs e)
        {
         //   lbl_tk.Text = Drop_timgt.SelectedItem.ToString();
        }

        protected void Button_more_Click(object sender, EventArgs e)
        {
            Response.Redirect("CTadm.aspx?act=Them_tt&id="+lbl_id.Text+"");
        }

        

       

      

       
    }
}